<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Event;

class Performance extends Base
{

    protected $name = 'performance';
    /**
     * 业绩新增
     */
    public static function addTotal($money)
    {
        $sys = \app\common\controller\Config::lists();
        try {
            $info = parent::whereMonth('create_time')->find();
            if (empty($info)) {
                $data = [
                    'money' => $money,
                    'settle_money' => $money,
                    'time' => date('Y-m'),
                ];
                parent::create($data);
            } else {
                $info->money += $money;
                $info->settle_money += $money;
                $info->save();
            }
            return ['code' => 1, 'msg' => '新增成功'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 结算
     */
    public static function settle()
    {
        $sys = \app\common\controller\Config::lists();
        try {
            $info = parent::whereMonth('create_time','last month')->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '数据不存在'];
            }
            if ($info->settle_money <= 0) {
                return ['code' => -1, 'msg' => '暂无结算业绩！'];
            }
            $t6 = User::where('level_id', 6)->column('id');
            if (!empty($t6)) {
                $t6money = round($info->settle_money * $sys['t_6'] / count($t6), 2);
                foreach ($t6 as $v) {

                    Target::Account()->basics($v, 'bonus_1', $t6money, '业绩分红', '+')
                        ->createBonus(0, 4);
                }
            }
            $t7 = User::where('level_id', 7)->column('id');
            if (!empty($t7)) {
                $t7money = round($info->settle_money * $sys['t_7'] / count($t7), 2);
                foreach ($t7 as $v) {

                    Target::Account()->basics($v, 'bonus_1', $t7money, '加权分红', '+')
                        ->createBonus(0, 5);
                }
            }
            //统计收入，则需使用
            Event::trigger('Statistics', ['key' => 'expend', 'value' => round($info->settle_money * ($sys['t_6'] + $sys['t_7']), 2)]);
            $info->settle_money = 0;
            $info->save();
            return ['code' => 1, 'msg' => '结算成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
